package logic

import (
	"context"
	"fmt"
	"vipshop/models/cache"
	"vipshop/models/mysql"
	"vipshop/pkg"

	"vipshop/viprpc/internal/svc"
	"vipshop/viprpc/viprpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatePasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdatePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePasswordLogic {
	return &UpdatePasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdatePasswordLogic) UpdatePassword(in *viprpc.UpdatePasswordRequest) (*viprpc.UpdatePasswordResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.VipUser
	mysql.DB.Debug().Where("account = ?", in.Account).Find(&user)

	if user.ID == 0 {
		return nil, fmt.Errorf("当前手机号不存在")
	}

	smsCode, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Account).Result()
	if smsCode != in.SendSmsCode {
		return nil, fmt.Errorf("短信验证码错误,请重新输入")
	}
	if pkg.Md5str(in.Password) == user.Password {
		return nil, fmt.Errorf("新密码和原密码一致，不允许修改")
	}

	user.Password = pkg.Md5str(in.Password)
	mysql.DB.Debug().Updates(&user)

	return &viprpc.UpdatePasswordResponse{
		UserId: int64(user.ID),
	}, nil
}
